package com.onesports.intelligent.k12.polarlight.service.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onesports.framework.kit.common.util.ParamUtils;
import com.onesports.intelligent.k12.polarlight.common.errors.exceptions.BusinessException;
import com.onesports.intelligent.k12.polarlight.domain.entity.sys.AccountRole;
import com.onesports.intelligent.k12.polarlight.domain.entity.sys.Role;
import com.onesports.intelligent.k12.polarlight.mapper.sys.AccountRoleMapper;
import com.onesports.intelligent.k12.polarlight.mapper.sys.RoleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Wsy
 **/
@Service
@RequiredArgsConstructor
public class AccountRoleService extends ServiceImpl<AccountRoleMapper, AccountRole> {
    private final AccountRoleMapper accountRoleMapper;
    private final RoleMapper roleMapper;


    /**
     * 根据账号id删除账号角色
     *
     * @param id 账号id
     */
    public void deleteByAccountId(String id) {
        //更改角色成员数量
        List<AccountRole> accountRoles = this.accountRoleMapper.selectList(new QueryWrapper<AccountRole>().lambda().eq(AccountRole::getAccountId, id));
        if (ParamUtils.isNotEmpty(accountRoles)) {
            List<String> roleIds = accountRoles.stream().map(AccountRole::getRoleId).collect(Collectors.toList());
            this.roleMapper.updateMemberAmount(roleIds, -1);
        }
        this.accountRoleMapper.delete(new QueryWrapper<AccountRole>().lambda().eq(AccountRole::getAccountId, id));
    }

    /**
     * 添加账号角色
     *
     * @param roleIds   角色ids
     * @param accountId 账号id
     */
    public void addAccountRole(List<String> roleIds, String accountId) {
        //校验角色是否存在
        List<Role> roles = this.roleMapper.selectBatchIds(roleIds);
        if (ParamUtils.isEmpty(roles) || roles.size() != roleIds.size()){
            throw new BusinessException("禁止选择不存在的角色，请重新选择");
        }
        List<AccountRole> accountRoles = roleIds.stream()
                .map(i -> AccountRole.builder()
                        .accountId(accountId)
                        .roleId(i)
                        .build())
                .collect(Collectors.toList());
        this.saveBatch(accountRoles);
        //修改角色成员数量
        this.roleMapper.updateMemberAmount(roleIds, 1);
    }


    public List<AccountRole> getByRoleIds(List<String> roleIds) {
        return this.accountRoleMapper.selectList(new QueryWrapper<AccountRole>().lambda().in(AccountRole::getRoleId, roleIds));
    }

}
